package org.zasadnyy.redlions.players.server.converters.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.mortbay.log.Log;
import org.zasadnyy.redlions.players.server.converters.PlayersConverter;
import org.zasadnyy.redlions.players.server.converters.TournamentsConverter;
import org.zasadnyy.redlions.players.server.model.PlayerObject;
import org.zasadnyy.redlions.players.shared.model.PlayerItem;
import org.zasadnyy.redlions.players.shared.model.TournamentItem;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class PlayersConverterImpl implements PlayersConverter {

	private TournamentsConverter tournamentConverter = new TournamentConverterImpl();

	@Override
	public PlayerItem toItem(PlayerObject object) {
		String stringKey = KeyFactory.keyToString(object.getId());
		Map<Integer, List<TournamentItem>> tournamentItems = tournamentConverter
				.toItemList(object.getTournaments());

		PlayerItem item = new PlayerItem(stringKey, object.getName(),
				object.getSurname(), object.getPhotoUrl(),
				object.getNativeCity(), object.getBirtday(),
				object.getPlaysFrom(), tournamentItems);
		return item;
	}

	@Override
	public PlayerObject toObject(PlayerItem item) {
		if (item == null) {
			Log.warn("Item to convert is null");
		}
		Set<Key> tournamentObjects = tournamentConverter.toObjectList(item
				.getTournaments());
		Key objectKey = null;
		if (item.getId() != null) {
			objectKey = KeyFactory.stringToKey(item.getId());
		}

		PlayerObject object = new PlayerObject(objectKey, item.getName(),
				item.getSurname(), item.getPhotoUrl(), item.getNativeCity(),
				item.getBirtday(), item.getPlaysFrom(), tournamentObjects);
		return object;
	}

	@Override
	public List<PlayerItem> toItemList(List<PlayerObject> objects) {
		List<PlayerItem> items = new ArrayList<PlayerItem>(objects.size());
		for (PlayerObject object : objects) {
			items.add(toItem(object));
		}
		return items;
	}

	@Override
	public List<PlayerObject> toObjectList(List<PlayerItem> items) {
		List<PlayerObject> objects = new ArrayList<PlayerObject>(items.size());
		for (PlayerItem item : items) {
			objects.add(toObject(item));
		}
		return objects;
	}

}
